package com.nepu.gmall.realtime.util;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.glassfish.hk2.utilities.PerThreadScopeModule;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenshuaijun
 * @create 2023-03-03 19:37
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> tClass, boolean underScoreToCamel) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // 创建一个存储结果的数据集
        ArrayList<T> resultList = new ArrayList<>();
        // 预处理sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 获取元数据信息
        ResultSetMetaData metaData = resultSet.getMetaData();
        // 获取查询出来的数据的列数
        int columnCount = metaData.getColumnCount();
        // 读取并封装数据
        while (resultSet.next()) {
            T t = tClass.newInstance();
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnName(i + 1);
                Object date = resultSet.getObject(columnName);
                // 判断是否需要下划线和驼峰之间的转换
                if (underScoreToCamel){
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                }
                // 数据封装
                BeanUtils.setProperty(t,columnName,date);
            }
            resultList.add(t);
        }

        // 关闭连接
        resultSet.close();
        preparedStatement.close();

        return resultList;
    }

    public static void main(String[] args) throws Exception {
        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();
        List<JSONObject> jsonObjects = queryList(connection, "select * from GMALL2022_REALTIME.DIM_BASE_TRADEMARK", JSONObject.class, true);
        System.out.println(jsonObjects.get(0));
        connection.close();

    }
}
